using System;

namespace EventBehaviorTree
{
    [Serializable]
    public class Selector : Container<ContainerMode>
    {
        public Selector(string workMode = "Async")
        {
            _workMode = (ContainerMode)Enum.Parse(typeof(ContainerMode), workMode);
            Condition = () => _stepCount == -1;//one sub nodes success; stepCounter -1 means success
        }

        public override void NodeEvent(NodeMessage nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMessage.Start:
                    _stepCount = 0;
                    ResetWorker();
                    _coroutineStarter.StartCoroutine(_worker);
                    _subNodes[0].NodeEvent(NodeMessage.Start);
                    return;
                case NodeMessage.Success:
                    _stepCount = -1;//-1 is just a signal, related to the definition of [Condition]
                    //when the [Condition] is true, the reporter will send message and reset itself.
                    return;
                case NodeMessage.Failure:
                    if (_stepCount < _subNodes.Count - 1)
                    {
                        _subNodes[++_stepCount].NodeEvent(NodeMessage.Start);
                        return;
                    }
                    SeniorNodeEvent(NodeMessage.Failure);//the last sub node will do this: all failed
                    //no node started successfully, so do not need to stop.
                    ResetWorker();
                    return;
                case NodeMessage.COMMAND_Stop:
                    ResetWorker();
                    StopAllSubNodes();
                    return;
                case NodeMessage.REQUEST_Abort://[CONSIDER]
                    ResetWorker();
                    StopAllSubNodes();
                    SeniorNodeEvent(NodeMessage.Success);//[HelpDoc]
                    return;
                default:
                    break;
            }
        }
    }
}
